package org.example.easybuy.controller;

import com.antherd.smcrypto.sm3.Sm3;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.easybuy.entity.User;
import org.example.easybuy.service.LoginService;
import org.example.easybuy.util.CustomResult;
import org.example.easybuy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/doLogin")
    public CustomResult login(@RequestBody User user) throws JsonProcessingException {
        Map<String,Object> map=loginService.login(user);
        return CustomResult.successResult().addResult("isExist","correct")
                .addResult("token",map.get("token"));
    }

    @GetMapping("/logout")
    public CustomResult logout(@RequestHeader(name="Authorization") String token )
    {
        String loginName= JwtUtil.getLoginName(token);
        //先查询是否存在这个token
        if(stringRedisTemplate.hasKey(loginName))
        {
            //如果存在就删除
            stringRedisTemplate.delete(loginName);
        }
        return CustomResult.successResult();
    }
}
